<template>
  <div class="add-order">
    <Dialog
      v-model="showDialog"
      :title="`${modelData.id ? '编辑' : '新增'}商家`"
      width="500px"
      :before-close="cancel"
      @open="openDialog"
    >
      <el-form
        v-loading="loading"
        ref="ruleFormRef"
        :model="ruleForm.formData"
        :rules="rules"
        label-width="95px"
        class="demo-ruleForm"
      >
        <el-form-item label="商家名称" prop="storeName">
          <el-input
            v-model="ruleForm.formData.storeName"
            maxlength="20"
            show-word-limit
            placeholder="请输入商家名称"
          />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="ruleForm.formData.userName"
            maxlength="20"
            show-word-limit
            placeholder="请输入用户名称"
          />
        </el-form-item>
        <el-form-item v-if="!modelData.id" label="密码" prop="password">
          <el-input
            type="password"
            v-model="ruleForm.formData.password"
            maxlength="20"
            show-word-limit
            show-password
            placeholder="请输入密码"
          />
        </el-form-item>

        <el-form-item label="供应商配置">
          <!-- <el-select v-model="ruleForm.formData.configId" placeholder="请选择供应商">
            <el-option
              v-for="item in payConfigList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select> -->
          <ScSelector
            v-model="ruleForm.formData.configId"
            placeholder="请选择供应商"
            type="config"
            :disabled="modelData.id"
            :params="{ attach: 'supplier' }"
          >
            <template #expand-pop="{ data }">
              <div v-if="data" class="detail-container">
                <div class="detail-text">
                  <h3>
                    {{ data.info.name }}
                  </h3>
                </div>
                <div class="detail-text_line">
                  配置类型：{{ data.info.externalTypeName }}
                </div>
                <div class="detail-text_line">
                  所属平台：{{ data.info.externalPlatformTypeName }}
                </div>
                <div class="detail-text_line">
                  配置标识：{{ data.info.unique }}
                </div>
                <div class="detail-text_line">
                  描述：{{ data.info.remark || "暂无" }}
                </div>
              </div>
            </template>
          </ScSelector>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input
            v-model.number="ruleForm.formData.phone"
            clearable
            placeholder="请输入手机号"
            maxlength="11"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="商家状态">
          <el-switch
            v-model="ruleForm.formData.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="商品审核">
          <div>
          <el-switch
            v-model="ruleForm.formData.goodsCheck"
            :active-value="1"
            :inactive-value="0"
          />
          <div class="tips">开启后，商品编辑、上架都需要人工审核通过后才能生效</div>
        </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button
            type="primary"
            @click="submitForm(ruleFormRef)"
            :loading="loading"
            >确定</el-button
          >
        </span>
      </template>
    </Dialog>
  </div>
</template>

<script lang="ts" setup>
import { addBusinesManagement, setBusinesManagement } from "@/api/product";
import type { FormInstance, FormRules } from "element-plus";
import sysConfigApi from "@/api/sysConfigApi";
const props = defineProps({
  showDialog: Boolean,
  modelData: {
    type: Object,
    default: {},
  },
});
const payConfigList = ref([] as any);
const { modelData, showDialog } = toRefs(props);
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  formData: {
    storeName: "",
    userName: "",
    password: "",
    status: 0,
    configId: "",
    phone: "",
    goodsCheck:0
  } as any,
});
const isMobileNumber = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入手机号码"));
  } else {
    if (String(value).length < 11) {
      callback(new Error("请输入正确的格式"));
    }
    callback();
  }
};
const rules = reactive<FormRules>({
  storeName: [{ required: true, message: "请输入商家名称", trigger: ["blur"] }],
  userName: [{ required: true, message: "请输入用户名称", trigger: ["blur"] }],
  password: [{ required: true, message: "请输入密码", trigger: ["blur"] }],
  // configId: [
  //   {
  //     required: true,
  //     message: "请选择供应商",
  //     trigger: "blur",
  //   },
  // ],
  phone: [
    // {
    //   required: true,
    //   message: "请输入手机号",
    //   trigger: "blur",
    // },
    // { min: 11,  message: '请输入正确的手机号格式', trigger: 'blur' },
    { required: true, validator: isMobileNumber, trigger: "blur" },
  ],
});
const openDialog = async () => {
  // await getConfigList();
  if (modelData.value.id) {
    ruleForm.formData = {
      storeName: modelData.value.storeName,
      userName: modelData.value.userName,
      password: "",
      configId: modelData.value.configId,
      phone: modelData.value.phone,
      status: modelData.value.status,
      id: modelData.value.id,
      goodsCheck:modelData.value.goodsCheck,
    };
  } else {
    ruleForm.formData = {
      storeName: modelData.value.storeName,
      userName: modelData.value.userName,
      password: "",
      status: 0,
      goodsCheck:0,
      configId: modelData.value.configId,
      phone: modelData.value.phone,
    };
  }
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      addMedalInfo();
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 获取供应商配置
const getConfigList = async () => {
  loading.value = true;
  let rs: any = await sysConfigApi.getConfigList({ externalType: "supplier" });
  if (rs.code == 200) {
    payConfigList.value = rs.payload;
  }
  loading.value = false;
};

// 新增商家
const addMedalInfo = async () => {
  loading.value = true;
  let rs: any = "";
  if (modelData.value.id) {
    rs = await setBusinesManagement(ruleForm.formData);
  } else {
    rs = await addBusinesManagement(ruleForm.formData);
  }

  if (rs.code === 200) {
    ElMessage({
      message: `${modelData.value.id ? "编辑" : "新增"}商家成功`,
      type: "success",
    });
    confirm();
  }
  loading.value = false;
};
const confirm = () => {
  emit("confirm");
  cancel();
};

const cancel = () => {
  ruleForm.formData = {
    storeName: "",
    userName: "",
    password: "",
    status: 0,
    goodsCheck:0
  };
  setTimeout(() => {
    ruleFormRef.value?.resetFields();
  }, 0);
  emit("cancel", "showDialog");
};
const emit = defineEmits(["confirm", "cancel"]);
</script>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}
.tips{
  font-size: 12px;
  color: #999;
}
</style>
